﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Blog.Repositories;
using MvcEngine.Blog.Models.Entities;
using MvcEngine.LinqToSqlProvider;

namespace MvcEngine.Blog.LinqToSqlProvider
{
    public class BlogPostCommentRepository : Repository, IBlogPostCommentRepository
    {
        public void Add(BlogPostComment entity)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Comments().InsertOnSubmit(entity);
                contextManager.Commit();
            }
        }

        public void Delete(Guid id)
        {
            using (var contextManager = CreateContextManager(false))
            {
                var comment = contextManager.Context.Comments().FirstOrDefault(c => c.Id == id);
                if (comment != null)
                {
                    contextManager.Context.Comments().DeleteOnSubmit(comment);
                    contextManager.Commit();
                }
            }
        }

        public IList<BlogPostComment> GetByBlog(Guid blogId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return (from c in contextManager.Context.Comments()
                        join p in contextManager.Context.Posts() on c.PostId equals p.Id
                        orderby c.CreatedDate descending
                        where p.BlogId == blogId
                        select c).ToList();
            }
        }

        public BlogPostComment Get(Guid id)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Comments().FirstOrDefault(c => c.Id == id);
            }
        }

        public IList<BlogPostComment> GetAll(Guid postId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Comments().Where(p => p.PostId == postId).OrderByDescending(p => p.CreatedDate).ToList();
            }
        }

        public void DeleteAll(Guid postId)
        {
            var comments = GetAll(postId);
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Comments().DeleteAllOnSubmit(comments);
                contextManager.Commit();
            }
        }
    }
}
